/*
 * AddressPager.java
 * business
 *
 * Created by ChenTao on 2017/3/13.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.widget.address;

import android.graphics.drawable.AnimationDrawable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.yidiandao.business.R;
import com.yidiandao.business.data.address.Area;
import com.yidiandao.business.data.model.AddressModel;
import com.yidiandao.business.data.model.IAddressModel;
import com.yidiandao.business.ui.widget.recyclerview.provider.ChooseAddressProvider;

import java.util.Iterator;
import java.util.List;

import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 地址管理中的单个页面
 *
 * <p>Created by ChenTao(chentao7v@gmail.com) on 2017/3/13 0013 15:16
 */
public class AddressPager {

    // NextPager
    private AddressPager mNextPager;

    private ViewPager mViewPager;

    private View mRootView;

    private RelativeLayout mLoadingLayout;

    private RecyclerView mRecyclerView;

    private ImageView mLoadingView;

    private MultiTypeAdapter mAdapter;

    private ChooseAddressProvider mItemProvider;

    private List<Area> mRecyclerViewData;

    private String mTitle;

    private String mInitTitle;

    private Area mSelectedData;

    private int defaultId = -1;

    private IAddressModel mAddressModel;

    // 正在操作当前页的标记
    // 避免多次点击同一个级下 的区域,如 同时点击贵州省/广东省引发bug
    private boolean processCurrentPager;

    private OnFinalPagerItemClickListener mFinalListener;

    public AddressPager(ViewPager viewPager) {

        mAddressModel = new AddressModel();
        mViewPager = viewPager;

        initViews(viewPager);
        setupAnimation();
        initRecyclerView(viewPager);
        initListeners();
    }

    private void initViews(ViewPager viewPager) {
        mRootView = View.inflate(viewPager.getContext(), R.layout.pager_address, null);
        mRecyclerView = (RecyclerView) mRootView.findViewById(R.id.recycler_view);
        mLoadingView = (ImageView) mRootView.findViewById(R.id.loading_view);
        mLoadingLayout = (RelativeLayout) mRootView.findViewById(R.id.loading_root);
    }

    private void setupAnimation() {
        AnimationDrawable drawable = (AnimationDrawable) mLoadingView.getDrawable();
        drawable.start();
    }

    private void initRecyclerView(ViewPager viewPager) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(viewPager.getContext()));
        mItemProvider = new ChooseAddressProvider();
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(Area.class, mItemProvider);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initListeners() {
        mItemProvider.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(Area area, int position) {
                processItemClickEvent(area, true, true, null);
            }
        });
    }

    private void processItemClickEvent(Area area, boolean autoSkipToNext, boolean triggerCallback,
            final OnPagerProcessListener listener) {

        // 标记当前页面正在处理
        if (processCurrentPager) {
            return;
        }
        processCurrentPager = true;

        // 将选择的逻辑设置到此处,避免重复点击
        area.setSelected(true);

        setTitle(area.getRegionName());

        // 每次点击一个Item时
        if (mSelectedData != null) {

            // 如果之前有选中的Item，则反选
            mSelectedData.setSelected(false);

            // 删除后面的Pager
            List<AddressPager> pagers = getPagerAdapter().getPagers();
            int posI = -1;
            for (int i = 0; i < pagers.size(); i++) {
                if (AddressPager.this.equals(pagers.get(i))) {
                    posI = i;
                    break;
                }
            }
            posI++;

            Iterator<AddressPager> iterator = pagers.iterator();
            int removeI = 0;
            while (iterator.hasNext()) {
                // 必须先调用 next()方法
                AddressPager next = iterator.next();

                if (posI == -1) {
                    break;
                }

                if (posI == removeI) {
                    // 重置 后面Pager的标题
                    next.setTitle(next.getInitTitle());
                    // 移除后面的Pager
                    iterator.remove();
                } else {
                    removeI++;
                }
            }
        }

        // 通知ViewPager数据已经发生改变
        notifyPagersDataSetChanged();
        // 通知RecyclerView item 选项已经改变
        notifyRecyclerViewDataChanged();

        // 保存当前选择的Item
        mSelectedData = area;

        // 处理下一级的Items
        processNextPager(area, autoSkipToNext, triggerCallback, listener);
    }

    private void processNextPager(Area area, boolean autoSkipToNext, boolean triggerCallback,
            OnPagerProcessListener listener) {
        // 没有下一页
        if (mNextPager == null) {

            // 没有下一页,标记当前页面处理完成
            processCurrentPager = false;

            // 回掉获取地址
            if (mFinalListener != null && triggerCallback) {
                mFinalListener.onFinalPagerItemClick();
            }
            return;
        }

        // 还有下一页
        getNextPagerDataFromServer(area, autoSkipToNext, listener);
    }

    public void showLoadingAnimation() {
        mLoadingLayout.setVisibility(View.VISIBLE);
    }

    public void hideLoadingAnimation() {
        mLoadingLayout.setVisibility(View.GONE);
    }

    private void getNextPagerDataFromServer(Area area, final boolean autoSkipToNext,
            final OnPagerProcessListener listener) {

        showLoadingAnimation();

        getAddressListByRegionId(
                area.getRegionId() + "", new IAddressModel.OnAddressListener() {
                    @Override
                    public void onSuccess(List<Area> areaList) {

                        // 标记当前页面处理完成
                        // 如果是用户自己点击的情况下会自动跳转到下一页
                        processCurrentPager = false;

                        hideLoadingAnimation();

                        // 添加 NextPager 到 PagerAdapter
                        getPagerAdapter().getPagers().add(mNextPager);
                        notifyPagersDataSetChanged();

                        if (autoSkipToNext) {
                            int skipPos = mViewPager.getCurrentItem() + 1;
                            if (skipPos < getPagerAdapter().getPagers().size()) {
                                mViewPager.setCurrentItem(skipPos);
                            }
                        }

                        // 设置 NextPager 的数据
                        mNextPager.setRecyclerViewData(areaList);

                        if (listener != null) {
                            listener.onPagerProcess(areaList);
                        }
                    }
                });
    }

    private AddressPagerAdapter getPagerAdapter() {
        return (AddressPagerAdapter) mViewPager.getAdapter();
    }

    private String getInitTitle() {
        return mInitTitle;
    }

    public void setInitTitle(String initTitle) {
        mInitTitle = initTitle;
        mTitle = initTitle;
    }

    private void notifyPagersDataSetChanged() {
        getPagerAdapter().notifyDataSetChanged();
    }

    public View getRootView() {
        return mRootView;
    }

    public String getTitle() {
        return mTitle;
    }

    private void setTitle(String title) {
        mTitle = title;
    }

    public void setRecyclerViewData(List<Area> areaList) {
        mRecyclerViewData = areaList;
        mAdapter.setItems(mRecyclerViewData);
        notifyRecyclerViewDataChanged();
    }

    private void notifyRecyclerViewDataChanged() {
        mAdapter.notifyDataSetChanged();
    }

    public Area getSelectedData() {
        return mSelectedData;
    }

    public int getDefaultId() {
        return defaultId;
    }

    public void setDefaultId(int defaultId) {
        this.defaultId = defaultId;
    }

    private void getAddressListByRegionId(String regionId,
            IAddressModel.OnAddressListener listener) {
        mAddressModel.getAreaList(regionId, AddressPager.class.getSimpleName(), listener);
    }

    public void autoSelectItemWithOriginId() {

        if (defaultId < 0) {
            return;
        }
        Area address = selectAddressOfList(mRecyclerViewData, defaultId, true);
        if (address != null) {
            processItemClickEvent(address, false, false, new OnPagerProcessListener() {
                @Override
                public void onPagerProcess(List<Area> areaList) {
                    if (mNextPager != null) {
                        mNextPager.autoSelectItemWithOriginId();
                    }
                }
            });
        }
    }

    private Area selectAddressOfList(List<Area> areaList, int originId, boolean isSelected) {
        for (Area area : areaList) {
            if (area.getRegionId() == originId) {
                area.setSelected(isSelected);
                return area;
            }
        }
        return null;
    }

    public void setNextPager(AddressPager nextPager) {
        mNextPager = nextPager;
    }

    void setOnFinalPagerItemClickListener(OnFinalPagerItemClickListener listener) {
        mFinalListener = listener;
    }

    public interface OnItemClickListener {
        void onItemClick(Area area, int position);
    }

    interface OnPagerProcessListener {
        void onPagerProcess(List<Area> areaList);
    }

    interface OnFinalPagerItemClickListener {
        void onFinalPagerItemClick();
    }
}
